import { imStore as imStore1 } from "@/store/imStore";
import { userData } from "@/store/userData";
import {TUIChatServer} from '@/pages/TUIKit/TUICore/server/index.ts'
import { getGroupUserLevel, loginOut } from '@/api/api'
export const customerService = async () => {

    const obj = {
        userId:'adminkefu',
        remark:'',
    }
    await addFriend(obj).catch(err=>{});


    let conversationId = 'C2Cadminkefu'
    return new Promise((resolve, reject) => {
      const imStore = imStore1();
      const TUIConversationServer = uni.$TUIKit.TUIConversationServer;
      imStore.setConversationID(conversationId)
  
        //uni.$TUIKit.TUIChatServer.updateStore(value.conversationID)
  
  
      //uni.$TUIKit.TUIChatServer.updateStore(conversationId)
	  /*
	  TUIConversationServer.setMessageRead(conversationId);
	  */
      TUIConversationServer.getConversationProfile(conversationId)
        .then(async (res: any) => {
          // 通知 TUIChat 关闭当前会话
          const { conversation } = res.data;
  
          imStore.setConversation(conversation)


          if(uni.$TUIKit.TUIChatServer){
            uni.$TUIKit.TUIChatServer.destroyed();
          }
  
  
  
          uni.$TUIKit.TUIChatServer = new TUIChatServer();
  
  
  
  
  
          await uni.$TUIKit.TUIChatServer.updateStore();

          //     uni.navigateTo({
          //         url:"/pages/TUIKit/TUIPages/TUIChat/index",
          //     });
  
          // resolve(true)
  
          //uni.$emit('handleScrollBottom')
			uni.navigateTo({
				url:'/pages/TUIKit/TUIPages/TUIChat/index?customerService=true',
				fail(err){
					console.log('navigateToeeeeeeeeeeeee')
					console.log('navigateToeeeeeeeeeeeee')
					console.log('navigateToeeeeeeeeeeeee')
					console.log(err)
				},
				success(){
					uni.$emit('handleScrollBottom');
				}
			});
          
        })
        .catch((err: any) => {
          uni.hideLoading();
          reject(err)
          console.warn("获取 group profile 异常 = ", err);
        });
    });
  };


export const getGroupAddList = async () => {
    // if(uni.$chat_isSDKReady){
    //     return;
    // }


    const IM_STORE = imStore1();

    const res = await getGroupApplicationList();
    const { code, data } = res;
    if (code !== 0) {
        return;
    }
    const { applicationList } = data;
    applicationList.forEach((item) => {
        item.application = JSON.parse(JSON.stringify(item));
        item.time = Number(String(item.messageKey).substring(0, 10));
    });

    const userIdList = applicationList.map((item) => item.applicant);
    const userListRes = await getUserProfile(userIdList);

    if (userListRes.code !== 0) {
        return;
    }
    const userArr = userListRes.data;
    const arr = applicationList.map((item, index) => {
        return {
            ...item,
            ...userArr[index],
            type: "group",
        };
    });

    console.log('getGroupAddList')
    console.log(arr);
    
    IM_STORE.setGroupApplicationList(arr);
};


export const handleJumpToChat = async (conversationId: any,getGroup:boolean,firstTimeInGroup:boolean) => {
  return new Promise((resolve, reject) => {
    const imStore = imStore1();
    const TUIConversationServer = uni.$TUIKit.TUIConversationServer;
    imStore.setConversationID(conversationId)

      //uni.$TUIKit.TUIChatServer.updateStore(value.conversationID)


    //uni.$TUIKit.TUIChatServer.updateStore(conversationId)
	/*
    TUIConversationServer.setMessageRead(conversationId);
	*/
    TUIConversationServer.getConversationProfile(conversationId)
      .then(async (res: any) => {
        // 通知 TUIChat 关闭当前会话
        const { conversation } = res.data;

        imStore.setConversation(conversation)


        if(conversationId === "@TIM#SYSTEM"){
            uni.navigateTo({
                url: "/pages/TUIKit/TUIPages/TUIChat/systemChat",
            });
            return;
        }




        if(getGroup){
            const {groupID} = conversation.groupProfile;
           const res:any = await getGroupProfile(groupID);
           imStore.updateConversationGroupProfile(res.data.group)
        }



        //console.log("create conversation response = ", res);

        // if (conversationId.slice(0, 5) === "GROUP") {
        //   const { name } = conversation.groupProfile;
        //   url = `${url}?conversationName=${name}`;
        // } else if (conversationId.slice(0, 3) === "C2C") {
        //   const { nick } = conversation.userProfile;
        //   url = `${url}?conversationName=${nick||conversation.userProfile.userID}`;
        // }
        uni.hideLoading();

        // const time = new Date().getTime();

        // let url = `/pages/TUIKit/TUIPages/TUIChat/index?time=${time}`





        
        // if(!webview){
        //     uni.preloadPage({url: url,success:()=>{},});
        // }
        if(uni.$TUIKit.TUIChatServer){
            uni.$TUIKit.TUIChatServer.destroyed();
        }



        uni.$TUIKit.TUIChatServer = new TUIChatServer();

        // if(firstTimeInGroup){
        //     await uni.$TUIKit.TUIChatServer.sendTextMessage('新人加入，请多关照。');
        // }




        await uni.$TUIKit.TUIChatServer.updateStore();
        uni.isGroup = false;



        if (conversation.type === "GROUP") {
            uni.isGroup = true;
            const groupId = conversation?.groupProfile?.groupID;
            const res:any = await getGroupUserLevel({groupId})
            const {flag,data} = res;
            if(flag!==1){
                return;
            }
            let obj = {}
            data.forEach(item=>{
                obj[item.id] = item.isVip
            })

            imStore.setVipMap(obj)
            
        } else if (conversation.type === "C2C"){
            const userId = conversation?.userProfile?.userID;
            const {code,data} = await getUserProfile([userId]);
            if(code!==0){
                return;
            }
            let obj = {}
            const USER_DATA = userData();
            obj[userId] = data[0].level;
            obj[USER_DATA.id] = USER_DATA.isVip;
            imStore.setVipMap(obj)
        }


                uni.navigateTo({
                    url:`/pages/TUIKit/TUIPages/TUIChat/index`,
                    fail(err){
                        console.log('navigateToeeeeeeeeeeeee')
                        console.log('navigateToeeeeeeeeeeeee')
                        console.log('navigateToeeeeeeeeeeeee')
                        console.log(err)
                    },
                    success(){
                        uni.$emit('handleScrollBottom');
                    }
                });

        return

                



            



        if(webview){

            console.log('ppppppppppppppp')
            console.log('ppppppppppppppp')
            console.log('ppppppppppppppp')
            webview.show();
            //console.log(webview)
            //webview?.show();
            // uni.$emit('handleScrollBottom')
            // setTimeout(()=>{
            //     uni.navigateTo({
            //         url:preloadPageUrl,
            //         fail(err){
            //             console.log('navigateToeeeeeeeeeeeee')
            //             console.log('navigateToeeeeeeeeeeeee')
            //             console.log('navigateToeeeeeeeeeeeee')
            //             console.log(err)
            //         }
            //     });
            // },0)
            // resolve(true)
        }else{
            console.log('ssssssssssssssssssssssss')
            console.log('ssssssssssssssssssssssss')
            console.log('ssssssssssssssssssssssss')
            console.log('ssssssssssssssssssssssss')
            console.log('ssssssssssssssssssssssss')

            uni.$emit('handleScrollBottom')
                setTimeout(()=>{
                    uni.navigateTo({
                        url:`/pages/TUIKit/TUIPages/TUIChat/index`,
                    });
                    resolve(true)
                },0)





        }



        
      })
      .catch((err: any) => {
        uni.hideLoading();
        reject(err)
        console.warn("获取 group profile 异常 = ", err);
      });
  });
};


export const getMessageList = async (obj:any) => {
    return new Promise((resolve, reject) => {
        //{conversationID: 'C2Ctest',nextReqMessageID}
        //isCompleted
        uni.$TUIKit
              .getMessageList(obj)
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "加入群失败！" });
                console.log(err);
                reject(err)
              });


    })

}

export const clearHistoryMessage = async (conversationId:string) => {
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .clearHistoryMessage(conversationId)
              .then((imResponse) => {
                resolve(imResponse)
              })
              .catch((err) => {
                console.log(err);
                reject(err)
              });


    })

}


export const handleJoinGroup = async ({groupID,msg}:any) => {

    return new Promise((resolve, reject) => {

        uni.$TUIKit
              .joinGroup({ groupID,applyMessage:msg })
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err) => {
                //uni.showToast({ title: "加入群失败！" });
                console.log(err);
                reject(err)
              });


    })

}

export const quitGroup = async (groupID:string) => {
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .quitGroup(groupID)
              .then((imResponse) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err) => {
                //uni.showToast({ title: "加入群失败！" });
                console.log(err);
                reject(err)
              });
    })

}
export const getConversationList= async () => {

    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getConversationList()
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取个人群列表失败！" });
                console.log(err);
                reject(err)
              });


    })

}




export const getGroupList= async () => {

    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getGroupList()
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取个人群列表失败！" });
                console.log(err);
                reject(err)
              });


    })

}

export const getGroupMemberProfile= async (params) => {
    // *params.groupID  string
    // *params.userIDList  []String
    // params.memberCustomFieldFilter  []String
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getGroupMemberProfile(params)
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取个人群列表失败！" });
                console.log(err);
                reject(err)
              });


    })

}

export const isGroupJoined = async (userId:string,groupID:string)=>{

    return new Promise(async (resolve,reject)=>{
        try {
            const params = {
                groupID,
                userIDList:[userId]
            }
            const result:any = await getGroupMemberProfile(params);
            const { data } = result;
            resolve(true)
        
        } catch (error) {
            const {code,message} = error;
            if(code===10007&&message.indexOf('only group member')!==-1){
                resolve(false)
            }else{
                reject(error)
            }

        }

    })

    return false;
}


export const changeGroupOwner = async (groupID:string,newOwnerID:string)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .changeGroupOwner({ groupID,newOwnerID})
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}
export const getGroupProfile = async (groupID:string)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getGroupProfile({ groupID, groupCustomFieldFilter: ['config'] })
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取群详情失败！" });
                console.log(err);
                reject(err)
              });
    })
}
export const getGroupMemberList = async (groupID:string,offset:number)=>{
    return new Promise((resolve, reject) => {
		//console.log(offset)
        uni.$TUIKit
              .getGroupMemberList({ groupID, count: 100, offset:offset })
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const updateGroupProfile = async (obj:any)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .updateGroupProfile(obj)
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const setGroupMemberNameCard = async (obj:any)=>{
    //{ groupID: 'group1', userID: 'user1', nameCard: '用户名片' }
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .setGroupMemberNameCard(obj)
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const setGroupMemberCustomField = async (obj:any)=>{
    //{ groupID: 'group1', memberCustomField: [{key: 'group_member_test', value: 'test'}]}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .setGroupMemberCustomField(obj)
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const getGroupApplicationList = async ()=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getGroupApplicationList()
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}


export const handleGroupApplication = async (obj:any)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .handleGroupApplication(obj)
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}


export const addFriend = async ({userId,wording,remark,source='web'}:any)=>{
    return new Promise((resolve, reject) => {



        console.log('1232445454545')
        console.log('1232445454545')
        console.log('1232445454545')
        console.log(source)

        try {
            uni.$TUIKit
              .addFriend({
                to: userId,
                source: `AddSource_Type_${source}`,
                remark,
                wording,
                type: uni.$TIM.TYPES.SNS_ADD_TYPE_BOTH,
              })
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                reject(err);
                console.log(err);
                //reject(err)
              });
            
        } catch (error) {
            uni.$TUIKit
                    .addFriend({
                        to: userId,
                        source: `AddSource_Type_${source}`,
                        remark,
                        wording,
                        type: uni.$TIM.TYPES.SNS_ADD_TYPE_SINGLE,
                    }).then((res:any)=>{
                        console.log(res);
                        resolve(res)
                    }).catch(()=>{
                        reject(err);
                    })
        }



    })
}

export const delFriend = async (userList:any)=>{
    return new Promise((resolve, reject) => {
        // TIM.TYPES.SNS_DELETE_TYPE_SINGLE 单向删除（只将 B 从 A 的好友表中删除，但不会将 A 从 B 的好友表中删除）
        // TIM.TYPES.SNS_DELETE_TYPE_BOTH 双向删除（将 B 从 A 的好友表中删除，同时将 A 从 B 的好友表中删除）
        uni.$TUIKit
              .deleteFriend({
                userIDList: userList,
                type: uni.$TIM.TYPES.SNS_DELETE_TYPE_SINGLE
              })
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}



export const getFriendProfile = async (userList:any)=>{
    return new Promise((resolve, reject) => {
        // TIM.TYPES.SNS_DELETE_TYPE_SINGLE 单向删除（只将 B 从 A 的好友表中删除，但不会将 A 从 B 的好友表中删除）
        // TIM.TYPES.SNS_DELETE_TYPE_BOTH 双向删除（将 B 从 A 的好友表中删除，同时将 A 从 B 的好友表中删除）
        uni.$TUIKit
              .getFriendProfile({userIDList:userList})
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取入群申请列表！" });
                console.log(err);
                reject(err)
              });


    })
}

export const updateFriend = async ({userId,remark}:any)=>{
    return new Promise((resolve, reject) => {
        // TIM.TYPES.SNS_DELETE_TYPE_SINGLE 单向删除（只将 B 从 A 的好友表中删除，但不会将 A 从 B 的好友表中删除）
        // TIM.TYPES.SNS_DELETE_TYPE_BOTH 双向删除（将 B 从 A 的好友表中删除，同时将 A 从 B 的好友表中删除）
        uni.$TUIKit
              .updateFriend({userID:userId,remark})
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取入群申请列表！" });
                console.log(err);
                reject(err)
              });


    })
}


export const checkFriend = async (userList:any)=>{
    return new Promise((resolve, reject) => {
        // TIM.TYPES.SNS_DELETE_TYPE_SINGLE 单向删除（只将 B 从 A 的好友表中删除，但不会将 A 从 B 的好友表中删除）
        // TIM.TYPES.SNS_DELETE_TYPE_BOTH 双向删除（将 B 从 A 的好友表中删除，同时将 A 从 B 的好友表中删除）
        
        uni.$TUIKit
              .checkFriend({
                userIDList: userList,
                type: uni.$TIM.TYPES.SNS_CHECK_TYPE_BOTH,
              })
              .then((imResponse:any) => {
                // 单向校验好友关系时可能的结果有：
                // - relation: TIM.TYPES.SNS_TYPE_NO_RELATION A 的好友表中没有 B，但无法确定 B 的好友表中是否有 A
                // - relation: TIM.TYPES.SNS_TYPE_A_WITH_B A 的好友表中有 B，但无法确定 B 的好友表中是否有 A
                // 双向校验好友关系时可能的结果有：
                // - relation: TIM.TYPES.SNS_TYPE_NO_RELATION A 的好友表中没有 B，B 的好友表中也没有 A
                // - relation: TIM.TYPES.SNS_TYPE_A_WITH_B A 的好友表中有 B，但 B 的好友表中没有 A
                // - relation: TIM.TYPES.SNS_TYPE_B_WITH_A A 的好友表中没有 B，但 B 的好友表中有 A
                // - relation: TIM.TYPES.SNS_TYPE_BOTH_WAY A 的好友表中有 B，B 的好友表中也有 A
                resolve(imResponse)
              })
              .catch((err:any) => {
                //uni.showToast({ title: "获取入群申请列表！" });
                console.log(err);
                reject(err)
              });


    })
}

export const acceptAddFriend= async ({userId,remark}:any)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .acceptFriendApplication({
                userID:userId,
                remark,
                type: uni.$TIM.TYPES.SNS_APPLICATION_AGREE_AND_ADD
              })
              .then((imResponse:any) => {
                resolve('success')
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}


export const deleteAddFriend= async (userId:any)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .deleteFriendApplication({
                userID:userId,
              })
              .then((imResponse:any) => {
                resolve('success')
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}

export const refuseAddFriend= async (userId:any)=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .refuseFriendApplication({
                userID:userId,
                type: uni.$TIM.TYPES.SNS_APPLICATION_SENT_TO_ME
              })
              .then((imResponse:any) => {
                resolve('success')
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}


export const setAddFriendRead= async ()=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .setFriendApplicationRead()
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}




export const getFriendList = async ()=>{
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getFriendList()
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}




export const getMyProfile = async ()=>{
    // {userIDList: ['10000000']}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getMyProfile()
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const updateMyProfile = async (params:any)=>{
    // {userIDList: ['10000000']}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .updateMyProfile(params)
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const getUserProfile = async (userIDList:any)=>{
    // {userIDList: ['10000000']}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getUserProfile({userIDList})
              .then((imResponse:any) => {
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}


export const getBlacklist = async ()=>{
    // {userIDList: ['10000000']}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .getBlacklist()
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}


export const addToBlacklist = async (userIDList:any)=>{
    // {userIDList: ['10000000']}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .addToBlacklist({userIDList: userIDList})
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}

export const removeFromBlacklist = async (userIDList:any)=>{
    // {userIDList: ['10000000']}
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .removeFromBlacklist({userIDList: userIDList})
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });


    })
}
export const setGroupMemberMuteTime = async (groupID:string,userID:string,bool:boolean)=>{
    // {userIDList: ['10000000']}
	let muteTime = 0;
	if(bool)muteTime = 315360000
	console.log(bool)
    return new Promise((resolve, reject) => {
        uni.$TUIKit
              .setGroupMemberMuteTime({groupID: groupID,userID:userID,muteTime:muteTime})
              .then((imResponse:any) => {
                console.log(imResponse);
                resolve(imResponse)
              })
              .catch((err:any) => {
                console.log(err);
                reject(err)
              });
    })
}



